Element.extend({
	 amongTo:function(elp,opts){
		var el=this;
		var elSize=el.getSize(),
		elpSize=elp.getSize();
		
		var options={width:2,height:2};
		if(opts){options=$merge(options,opts);}
		el.setStyles({
		'position':'absolute',
		'opacity':1,
        'visibility':'visible',
        'display':''
		});
		var pos={
		'top':Math.abs(((elpSize.size.y/options.height).toInt())-((elSize.size.y/options.height).toInt())+elp.getPosition().y+elpSize.scroll.y),
		'left':Math.abs(((elpSize.size.x/options.width).toInt())-((elSize.size.x/options.width).toInt())+elp.getPosition().x+elpSize.scroll.x)
		}
		if(options.Fx){
		 new Fx.Styles(el).start(pos);
		}else{
		 el.setStyles(pos);
		}
		return this;	
	 },
      zoomImg:function(maxwidth,maxheight,v){
	   if(this.getTag()!='img'||!this.width)return;
       var thisSize={'width':this.width,'height':this.height};
		   if (thisSize.width>maxwidth){
		      var overSize=thisSize.width-maxwidth;
			  var zoomSizeW=thisSize.width-overSize;
			  var zommC=(zoomSizeW/thisSize.width).toFloat();
			  var zoomSizeH=(thisSize.height*zommC).toInt();
			  $extend(thisSize,{'width':zoomSizeW,'height':zoomSizeH});
		   }
		   if (thisSize.height>maxheight){
		      var overSize=thisSize.height-maxheight;
			  var zoomSizeH=thisSize.height-overSize;
			  var zommC=(zoomSizeH/thisSize.height).toFloat();
			  var zoomSizeW=(thisSize.width*zommC).toInt();
			  $extend(thisSize,{'width':zoomSizeW,'height':zoomSizeH});
		   }
	   if(!v)return this.set(thisSize);
	   return thisSize;
	 },
	 getPadding:function(){
	 	return {
			'x':this.getStyle('padding-left').toInt()||0+this.getStyle('padding-right').toInt()||0,
			'y':this.getStyle('padding-top').toInt()||0+this.getStyle('padding-bottom').toInt()||0
		}
	 },
	 getMargin:function(){
	 	return {
			'x':this.getStyle('margin-left').toInt()||0+this.getStyle('margin-right').toInt()||0,
			'y':this.getStyle('margin-top').toInt()||0+this.getStyle('margin-bottom').toInt()||0
		}
	 },
	 getBorderWidth:function(){
	 	return {
			'left':this.getStyle('border-left-width').toInt()||0,
			'right':this.getStyle('border-right-width').toInt()||0,
			'top':this.getStyle('border-top-width').toInt()||0,
			'bottom':this.getStyle('border-bottom-width').toInt()||0,
			'x':this.getStyle('border-left-width').toInt()||0+this.getStyle('border-right-width').toInt()||0,
			'y':this.getStyle('border-top-width').toInt()||0+this.getStyle('border-bottom-width').toInt()||0
		}
	 },
	 getTrueWidth:function(){
	 return this.getSize().size.x-(
		 this.getMargin().x+
		 this.getPadding().x+
		 this.getBorderWidth().left+
		 this.getBorderWidth().right
		 );
	 },
	 getTrueHeight:function(){
	  return this.getSize().size.y-(
		 this.getMargin().y+
		 this.getPadding().y+
		 this.getBorderWidth().top+
		 this.getBorderWidth().bottom
		 );
	 },
	 getCis:function(){
			return this.getCoordinates();
		},
	  show:function(){
	  this.fireEvent('onshow',this);
	  return 	$chk(this)?this.setStyle('display',''):this;
	  },
	  hide:function(){
	  this.fireEvent('onhide',this);
	   return 	$chk(this)?this.setStyle('display','none'):this;
	  },
      isDisplay:function(){
         if(this.getStyle('display')=='none'||(this.offsetWidth+this.offsetHeight)==0){
            return false;
         }
         return true;
      },
	  getSelectedRange: function() {
		if (!Browser.Engine.trident) return {start: this.selectionStart, end: this.selectionEnd};
		var pos = {start: 0, end: 0};
		var range = this.getDocument().selection.createRange();
		if (!range || range.parentElement() != this) return pos;
		var dup = range.duplicate();
		if (this.type == 'text') {
			pos.start = 0 - dup.moveStart('character', -100000);
			pos.end = pos.start + range.text.length;
		} else {
			var value = this.value;
			var offset = value.length - value.match(/[\n\r]*$/)[0].length;
			dup.moveToElementText(this);
			dup.setEndPoint('StartToEnd', range);
			pos.end = offset - dup.text.length;
			dup.setEndPoint('StartToStart', range);
			pos.start = offset - dup.text.length;
		}
		return pos;
	  },
	  selectRange: function(start, end) {
		if (Browser.Engine.trident) {
			var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
			start = this.value.substr(0, start).replace(/\r/g, '').length;
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd('character', start + diff);
			range.moveStart('character', start);
			range.select();
		} else {
			this.focus();
			this.setSelectionRange(start, end);
		}
		return this;
	}
	});
  String.extend({
	  format:function(){
        if(arguments.length == 0)
          return this;
         var reg = /{(\d+)?}/g;
         var args = arguments;
		 var string=this;
         var result = this.replace(reg,function($0, $1) {
           return  args[$1.toInt()]||"";
          }
     )
     return result;
  }
});

void function(){
        broswerStore=null;
        withBroswerStore=function(callback){
                 if(broswerStore)
                 return  callback(broswerStore);
                  window.addEvent('domready',function(){
                      if(broswerStore=new BrowserStore()){
                          callback(broswerStore);
                       }else{
                          window.addEvent('load',function(){
                            callback(broswerStore=new BrowserStore());
                          });
                       }
                  });
         };
}();


var MessageBox=new Class({
    options:{
       delay:1,
       onFlee:$empty,
       FxOptions:{
       }
    },
    initialize:function(msg,type,options){
       $extend(this.options,options);
       this.createBox(msg,type);
       
    },
    flee:function(mb){
       var mbFx=new Fx.Styles(mb,this.options.FxOptions);
       var begin=false;
       var obj=this;
       mb.addEvents({
          mouseenter:function(){
             if(begin)
             mbFx.pause();
          },
          mouseleave:function(){
            if(begin)
            mbFx.resume();
          }
       });
       (function(){
           begin=true;
           mbFx.start({
              'left':0,
              'opacity':0
           }).chain(function(){
              this.element.remove();
              begin=false;
         
              if(obj.options.onFlee){
                obj.options.onFlee.apply(obj,[obj]);
              }
              if(window.MessageBoxOnFlee){
                    window.MessageBoxOnFlee();
                    window.MessageBoxOnFlee=$empty();
              }
           });
       }).delay(this.options.delay*1000);
       
    },
    createBox:function(msg,type){
      var msgCLIP=/<h4[^>]*>([\s\S]*?)<\/h4>/;
      var tempmsg=msg;
      if(tempmsg.test(msgCLIP)){
         tempmsg.replace(msgCLIP, function(){
            msg=arguments[1];
            return '';
        });
      }
      var box = new Element('div').setStyles({
          'position':'absolute',
          'visibility':'hidden',
          'width':200,
          'opacity':0,
          'zIndex':65535
      }).inject(document.body);
      var obj=this;
  
      box.addClass(type).setHTML("<h4>",msg,"</h4>").amongTo(window).effect('opacity').start(1).chain(function(){
          obj.flee(this.element);
          
      }); 
      return box;
    }

});

MessageBox.success=function(msg,options){
    return new MessageBox(msg||"操作成功!",'success',options);
};
MessageBox.error=function(msg,options){
    return new MessageBox(msg||"操作失败!",'error',options);
};
MessageBox.show=function(msg,options){
    if(msg.contains('failedSplash')){
        return new MessageBox(msg||"操作失败!",'error',options);
    }return new MessageBox(msg||"操作成功!",'success',options);
   
};

_open = function(url,options){
   options = $extend({
     width:window.getSize().x*0.8,
     height:window.getSize().y
   },options||{})
   var params = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width={width},height={height}';
       params = params.substitute(options);
       
   window.open(url||'about:blank','_blank',params);

};

/*fix Image size*/
var fixProductImageSize=function(images,ptag){
        if(!images||!images.length)return;
         images.each(function(img){
             if(!img.src)return;
             new Asset.image(img.src,{
                  onload:function(){
                  var imgparent=img.getParent((ptag||'a'));
                  if(!this||!this.get('width'))return imgparent.adopt(img);
				  var imgpsize={x:imgparent.getTrueWidth(),y:imgparent.getTrueHeight()};
				  var nSize=this.zoomImg(imgpsize.x,imgpsize.y,true);
                  img.set(nSize);
                  var _style={'margin-top':0};
                  if(img&&img.get('height'))
                  if(img.get('height').toInt()<imgpsize.y){
    				     _style=$merge(_style,{'margin-top':(imgpsize.y-img.get('height').toInt())/2});
    				  }
                     img.setStyles(_style);
                     return true;
                  },onerror:function(){
                    
                  }
             });
         });
};

(function(){

 var Request_Cache={
	  cache:{}, 
	  getCache:function(target,body,fn){
	  	  var text;
		 if(text=target.retrieve('cache:uid'))
		//  if(text=this.cache['cache_'+target.uid])
		  return this.progress(text,body,fn);
		  return false;
	  },
	  progress:function(text,body,fn){
		 var javascript,
		 html = text.stripScripts(function(script){
			javascript = script;
		 });
		 if(body)body.set('html',html);
		 Browser.exec(javascript);
		 if(fn)fn(text);
		 return text;
	  },
	  setCache:function(target,value){
	     target.store('cache:uid',value);
		// this.cache['cache_'+target.uid]=value;
	  }
 };
 
 var Dialog =this.Dialog=new Class({
      Implements:[Options,Events],  
      options:{
          iframe:false,     
          title:'',     
          width:342,
          data:'',
          height:187,
          target:'',
		  rela:'',
		  method:'post',
		  singlon:true,
		  onShow:function(){
		  	this.dialog.setStyles({'visibility':'visible','opacity':'0'}).fade('in');
		  },
		  offset: {x: 70, y: 0},
		  callback:$empty,
          diaglogCls:'dialog'       
      },
      initialize:function(url,options){
          this.url=url;
          this.setOptions(options);
          options=this.options;

          var dialog = this.dialog= new Element('div',{'class':options.diaglogCls}).set('html',$('dialog-theme').value.substitute({
                          title:options.title,content:'loading....'
                       })).setStyles({visibility:'hidden',width:0}).inject(document.body);


		  if(options.singlon&&Dialog.singlon['uid'])Dialog.singlon['instance'].close();
		  Dialog.singlon={'uid':$uid(dialog),'instance':this};

          this.body=dialog.getElement('.dialog-content'); 
		  dialog.addEvent('callback',options.callback.bind(this));

          if(options.iframe) 
          this.iframe=new Element('iframe',{src:'javascript:void(0);',styles:{position:'absolute',
               zIndex:-1,border:'none',top:0,left:0,'filter':'alpha(opacity=0)'},width:'100%',height:'100%'}).inject(this.body.empty());

          this.show();
      },
      request:function(url,options){
          if(options.iframe)return this.iframe.set('src',url+'?'+options.data).addEvent('load',this.success.bind(this));
          if(ajax)ajax.cancel();
		  var target=$(options.target);

		  if(Request_Cache.getCache(target,this.body)) return this.success();

          var ajax= new Request.HTML({
             url:url,
             update:this.body,
             method:options.method,
             data:options.data,
             onFailure:this.close.bind(this),
			 onSuccess:function(){
				 Request_Cache.setCache(target,ajax.response.text)
				 this.success();
			 }.bind(this)
          }).send();
      },
	  success:function(){
		 if(this.props)this.fireEvent('position');			
		 this.fireEvent('success');
	  },
      show:function(){
         var closebtn=$E('*[isCloseDialogBtn]',this.dialog),options=this.options;
         if(closebtn)closebtn.addEvent('click',this.close.bind(this));
         if(!options.target)return this.dialog.amongTo(window);

         this.dialog.setStyles({position: 'absolute', width:options.width,height:options.height});
         this.fireEvent('show').position({page:options.target.getPosition()},options.rela);

		 (function(){
			document.addEvent('click',function(e){
				var target=$(e.target),diaglogCls=options.diaglogCls;
				if(!target.hasClass(diaglogCls)&&!target.getParent('.'+diaglogCls))
				this.close.call(this);
				document.removeEvent('click',arguments.callee);
			}.bind(this));
		 }).delay(200,this);

		 this.request(this.url,options);
      },
	  position: function(event,rela){
			var size = (rela||window).getSize(), scroll = (rela||window).getScroll(),
				dialog = {x: this.dialog.offsetWidth, y: this.dialog.offsetHeight},
				props = {x: 'left', y: 'top'}, obj = {};
			for (var z in props){
				obj[props[z]] = event.page[z] + this.options.offset[z];
				if ((obj[props[z]] + dialog[z] - scroll[z]) > size[z] && z!='y'){
					obj[props[z]] = event.page[z] + this.options.offset[z] - dialog[z];
					this.props=true;
				}
			}
			this.dialog.setStyles(obj);
	  },
      close:function(){
		  try{
			  this.fireEvent('close').dialog.remove();
		  }catch(e){}
      }
});
	Dialog.singlon={};
})();



/*AutoSize*/
var AutoSize = new Class({
	initialize: function(elements,hw) {
		this.elements = $$(elements);
		this.doAuto(hw);
	},
	doAuto: function(hw) {
		if(!hw) { hw = 'height'; }
		var max = 0,
			prop = (typeof document.body.style.maxHeight != 'undefined' ? 'min-' : '') + hw; //ie6 ftl
			offset = 'offset' + hw.capitalize();
		this.elements.each(function(element,i) {
			var calc = element[offset];
			if(calc > max) { max = calc; }
		},this);
		this.elements.each(function(element,i) {
			element.setStyle(prop,max - (element[offset] - element.getStyle(hw).replace('px','')));
		});
		return max;
	}
});